package easytalk.connectivity.googletalk;

import java.io.IOException;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.packet.VCard;

import common.EasyChatEnvironment;
import common.EasyTalkException;
import common.Locutor;

public class GoogleTalkPacketListener implements PacketListener {

	private Locutor locutor = null;
	Logger logger = Logger.getLogger(this.getClass());
	
	public GoogleTalkPacketListener(Locutor locutor) {
		this.locutor = locutor;
		
		
		FileAppender appender;
		try {
			appender = new FileAppender(new PatternLayout(),this.getClass() + ".log");
			logger.addAppender(appender);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void processPacket(Packet arg0) {
		Locutor locutor = null; 
		logger.info("packet from " + arg0.getFrom());
		if (locutor == null) {
			
			try {
				locutor = EasyChatEnvironment.getInstance().getLocutorById(arg0.getFrom(),new GoogleTalkIdComparator());
			} catch (EasyTalkException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
		}
			
		locutor.setPresent(true);
		if (!locutor.isPictureLoaded())
			if (arg0.toXML().contains("photo"))
		try {
			VCard card = new VCard();
			card.load(((GoogleTalkConnection)(locutor.getParentSet().getConnection())).getConnection(), locutor.getId());
			byte[] avatar = card.getAvatar();
			if (avatar != null) {
				locutor.setImage(card.getAvatar());
				
			}

		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
		EasyChatEnvironment.getInstance().update();

	}

}
